#include "text.h"

namespace animationagent {


Text::Text(TTF_Font *f) :
    surface(NULL)
{
    font = f;
}

Text::Text(TTF_Font *f, const char *s) :
    surface(NULL)
{
    font = f;
    if (s != NULL) {
        str.append(s);
    }
    rerender_text();
}

Text::~Text()
{
    SDL_FreeSurface(surface);
}

void Text::set_text(const char *s)
{
    str.clear();
    if (s != NULL) {
        str.append(s);
    }
    rerender_text();
}

void Text::append_text(const char *s)
{
    if (s != NULL) {
        str.append(s);
    }
    rerender_text();
}

const char *Text::get_text()
{
    return str.getChars();
}

void Text::draw(SDL_Surface *screen)
{
    if (!visible) {
        return;
    }
    Widget::draw(screen);
}

void Text::update()
{
    p_surface = surface;
    Widget::update();
}

void Text::set_bgcolor(SDL_Color &c)
{
    Widget::set_bgcolor(c);
    rerender_text();
}

void Text::set_fncolor(SDL_Color &c)
{
    Widget::set_fncolor(c);
    rerender_text();
}

void Text::rerender_text()
{
    //SDL_Surface *tmp = NULL;
    //Uint32 rmask, gmask, bmask, amask;
    if (surface != NULL) {
        SDL_FreeSurface(surface);
    }

    if (str.getChars() == NULL) {
        return;
    }
    bool tmpvisible = visible;
    if (tmpvisible) {
        set_visible(false);
    }
    surface = TTF_RenderUTF8_Solid(font, str.getChars(), fncolor);
    if (surface == NULL) {
        return;
    }
#if 0
    /* SDL interprets each pixel as a 32-bit number, so our masks must depend
       on the endianness (byte order) of the machine */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x00000000;
#else
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0x00000000;
#endif
    surface = SDL_CreateRGBSurface(SDL_SWSURFACE, tmp->w, tmp->h, 32,
                         rmask, gmask, bmask, amask);
    //surface = SDL_DisplayFormatAlpha(tmp);
    SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, bgcolor.r, bgcolor.g, bgcolor.b));
    SDL_BlitSurface(tmp, NULL, surface, NULL);
    SDL_SetColorKey(surface, SDL_SRCCOLORKEY | SDL_RLEACCEL,
                    SDL_MapRGB(surface->format, bgcolor.r, bgcolor.g, bgcolor.b));
    SDL_SetAlpha(surface, SDL_SRCALPHA, 0x80);
    SDL_FreeSurface(tmp);
#endif
    allocation.w = surface->w;
    allocation.h = surface->h;
    if (tmpvisible) {
        set_visible(true);
    }
}


}
